package com.example.demo.service.impl;

import com.example.demo.dao.Goods;
import com.example.demo.dao.GoodsExample;
import com.example.demo.dao.ImagePath;
import com.example.demo.dao.ImagePathExample;
import com.example.demo.mapper.GoodsMapper;
import com.example.demo.mapper.ImagePathMapper;
import com.example.demo.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 业务层：商品
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    ImagePathMapper imagePathMapper;


    //展示商品列表
    @Override
    public List<Goods> listGoods(String keyword) {
        keyword="%"+keyword+"%";
        GoodsExample example = new GoodsExample();
        example.or().andGoodsnameLike(keyword);
        return goodsMapper.selectByExample(example);
    }

    //删除选中的单上商品
    @Override
    public int deleteGoodsByPrimaryKey(Integer id) {
        return goodsMapper.deleteByPrimaryKey(id);
    }

    //删除选中的多行商品
    @Override
    public int multiDelGoods(String ids) {
        GoodsExample example = new GoodsExample();
        List<String> list = Arrays.asList(ids.split(","));
        List<Integer> ilist = list.stream().map(Integer::parseInt).collect(Collectors.toList());
        example.or().andGoodsidIn(ilist);
        return goodsMapper.deleteByExample(example);
    }

    //获取选中的商品的详细信息
    @Override
    public Goods findGoodsByPrimaryKey(Integer id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    //更新修改后的商品信息
    @Override
    public int updateGoods(Goods goods) {
        return goodsMapper.updateByPrimaryKeySelective(goods);
    }

    //添加商品信息
    @Override
    public Integer addGoods(Goods goods) {
        goodsMapper.insertSelective(goods);
        return goods.getGoodsid();
    }
    //将图片路径存到数据库中
    @Override
    public void addImagePath(ImagePath imagePath) {
        imagePathMapper.insertSelective(imagePath);
    }



    //-------------------------------------------------------------------前台查询-------------------------------------------------
    //查询所有
    @Override
    public List<Goods> goods() {
        return goodsMapper.listAll();
    }

    //按id查询
    public Goods findgoods(Integer id ){return goodsMapper.findByPrimaryKey(id);}

    @Override
    public List<ImagePath> findImage(Integer id) {
        ImagePathExample imagePathExample = new ImagePathExample();
        ImagePathExample.Criteria criteria = imagePathExample.createCriteria();
        criteria.andGoodidEqualTo(id);
        return imagePathMapper.selectByExample(imagePathExample);
    }
}
